import { createRouter, createWebHistory } from 'vue-router'
import AppLayout from '@/layout/AppLayout.vue'
import NotFound from '@/components/NotFound.vue';
import webapi from '@/utils/webapi';


const views = import.meta.glob('@/views/**/*.vue')
const getComponent = (c:string)=>{
  let res;
  for(const path in views){
    const component = path.split('views')[1].split('.vue')[0];
    if(component === c){
      res = ()=> views[path]();
    }
  }
  return res;
}

const buildRoute =(routePath:string,routeComponent:string,title:string, icon:string)=>{
  return {
    path :routePath,
    component: getComponent(`/${routeComponent}`),
    meta:{
      title:title || '网页标题',
      icon : icon || 'dashboard',
      keepalive: true
    }
  }
}

const staticRoute:Array<any> = [
  {
    path: '/',
    component:AppLayout,
    children:[
      buildRoute('/','HomeView','首页','')
    ]
  },
  buildRoute('/login','LoginView','登录',''),
  // {
  //   path:'/login',
  //   component:()=>import('@/views/LoginView.vue')
  // },
  {
    path:'/:catchAll(.*)',
    component:NotFound,
    meta:{
      title:'404'
    }
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: staticRoute
})

router.beforeEach((to, from,next)=>{
  const access_token = "Brear "
  if(to.path !=='/login' && to.name !=='Test' && !access_token){
    next({name:'/login',query:{redirect: to.fullPath}});
  }else{
    next()
  }
})

router.afterEach((to,from)=>{
  from
  document.title = `${to.meta.title}`;
})

const _fixRouteComponent = (items: any[])=>{
  items.forEach((o) =>{
    o.meta.dynamic = true
    o.component = getComponent(`/${o.component}`);
    if(o.children) {
      _fixRouteComponent(o.children)
    }
  })
}

const refreshRouter = async () =>{
  try{
    // const responese = await webapi.get('/api/getRoutes');
    const responese = await webapi.get('/data/data.json');
    const result = responese.data;
    router.getRoutes()
      .filter((o)=>o.meta.dynamic)
      .map((o)=>o.name)
      .forEach((o:any)=>router.removeRoute(o));

      _fixRouteComponent(result);

    result.forEach((o:any)=>{
      router.addRoute(o);
    })
  }catch(error){
    console.log(error)
  }
}

export {router, refreshRouter}
